Repository navigation
feat(api): honour caller cancellation in kimi code and its oauth refresh (#1311 split u3) - #2803
easonLiangWorldedtech wants to merge 3 commits into
Conversation
…-Org#1311 split u0) Unit u0 of the split plan in Zoo-Code-Org#2799. It carries the shared helpers that the provider units of Zoo-Code-Org#1311 consume, and nothing provider-specific. - abort-signal.ts: mergeAbortSignalAndTimeout, rejectOnAbort, and the timeout classification helpers (isTimeoutAbort, createTimeoutError). - error-handler.ts: handleOpenAIRequestError keeps an HTTP failure's identity over a racing abort and reports a deadline as TimeoutError. - request-timeout.ts: getRequestTimeoutMs for the per-request SDK timeout. - test-utils/errors.ts: captureError, used by the cancellation rows of the provider units. Evidence: 643 rows across the utils and test-utils specs pass; tsc --noEmit clean; eslint --prune-suppressions --max-warnings=0 clean; prettier clean.
…Org#1311 split u1) Unit u1 of the split plan in Zoo-Code-Org#2799. It carries openai.ts and the OpenAI-compatible base, with their cancellation rows. - The two abort contracts stay apart: the caller's signal goes to the request each route issues, and a mid-flight abort or a raw SDK abort becomes the provider's contract error with the failure kept as the cause. Each request site normalizes its own failure, including the Responses completion. - A stream failure is a flag beside its value, so a rejection carrying `undefined` still reaches the handler, and the recorded usage is yielded before the error. A usage frame the SDK already returned is recorded before the abort break. - The Responses completion forwards the merged caller and deadline signal, so the deadline stays armed while the SDK reads the JSON body. - Request creation is raced against the request signal, so a 429 backoff sleep cannot outlast a deadline. Evidence: openai, base-provider and cancellation rows 725 pass; tsc --noEmit clean; eslint --prune-suppressions --max-warnings=0 clean; prettier clean.
…esh (Zoo-Code-Org#1311 split u3) Unit u3 of the split plan in Zoo-Code-Org#2799. Stacked on u1 (Zoo-Code-Org#2801). - The Kimi Code handler forwards the caller's signal through model discovery and the completion request, and retries once after a 401 refresh. - The OAuth refresh keeps the pair the server rotated: a cancelled waiter no longer rolls back the write it was making, the shared POST is never aborted once sent, an older refresh cannot clear a newer one's commit marker, and every credential write runs on one chain. A store failure after a rotation keeps the pair in memory. - The invalid_grant clear runs on that chain with the generation re-checked inside. Evidence: kimi provider, oauth, fetcher and model-catalog rows 201 pass; tsc --noEmit clean; eslint --prune-suppressions --max-warnings=0 clean; prettier clean.
Review statusThanks for contributing. This comment tracks the review sequence and the next action. Current step: Fix the failing required CI checks; awaiting-maintainer requires CI and automated review completion. Review-state labels are managed by this workflow; do not edit them manually. |
Pre-merge checks:
|
| Check name | Status | Explanation |
|---|---|---|
| Regression Evidence | The changed behavior is cancellation handling in the Kimi Code provider, its model fetcher, and the OAuth manager. I compared 91c6af4 with dfb71c2 and read the source diff and the new tests. Change… | |
| Security Boundaries | The PR (Zoo-Code-Org/Zoo-Code #2803, author easonLiangWorldedtech, head split/1311-u3-kimi-code, base main) adds cancellation handling to the Kimi Code provider and its OAuth refresh. I diffed the uni… |
|
| Persistence Integrity | The changed persistence paths were checked in src/integrations/kimi-code/oauth.ts (diff against origin/main, which includes the u0 and u1 ancestor changes). No changed path meets the FAIL condition. E… | |
| Lifecycle Resource Cleanup | The PR diff (base 91c6af4 to HEAD dfb71c2) changes the Kimi Code provider, its model fetcher, and the OAuth manager. I checked each changed lifecycle path for a leaked listener, timer, watcher, or tas… |
Full details: Regression Evidence
-
Explanation
The changed behavior is cancellation handling in the Kimi Code provider, its model fetcher, and the OAuth manager. I compared 91c6af4 with dfb71c2 and read the source diff and the new tests. Changed behavior and the tests that cover it: - getKimiCodeModels (fetchers/kimi-code.ts): a pre-aborted signal, an in-flight abort, and a deadline with a live signal are covered in fetchers/tests/kimi-code.spec.ts (lines 87-153). The test layer is the fetcher unit. - KimiCodeHandler.createMessage and completePrompt: an already-aborted signal, abort during model preparation, abort before the 401 retry, forwarded signal and timeout options, and a streaming SDK abort are covered in api/providers/tests/kimi-code.spec.ts (lines 163-191, 327-413, 490-582). Abort during discovery that resets the single discovery attempt is covered at lines 447-488. The negative case for ordinary discovery failure is covered at lines 256-284. - OAuth cancellation (oauth.ts): covered in integrations/kimi-code/tests/oauth.spec.ts and kimi-code.oauth-cancellation.spec.ts. Rows include caller abort normalization to AbortError (lines 712-790), a native fetch failure that races an abort and is rethrown unchanged (742), a deadline timeout that is not normalized (156-212), abort during the credential read (561-592), no token POST for an unenrolled caller (kimi-code.oauth-cancellation.spec.ts 33-67), and a waiter detaching while the shared POST continues (594-634 and the cancellation spec at 69-130). Sign-out fence, commit ownership, and storage-failure rows are also present. Tests use the public API with fetch and SecretStorage doubles. They do not copy implementation logic. The negative, error, and unset cases I checked are present. Minor observations, not treated as failures: - completePrompt has no test for abort during model preparation. The createMessage counterpart exists (line 384). The inherited OpenAiHandler.completePrompt also checks the signal on entry, so a regression there is unlikely to go unnoticed. - No UI change, so no snapshot is required. I did not run the test suite. Evidence comes from source and test reading only. The PR states that 201 rows pass.
Full details: Security Boundaries
-
Explanation
The PR (Zoo-Code-Org/Zoo-Code
#2803, author easonLiangWorldedtech, head split/1311-u3-kimi-code, base main) adds cancellation handling to the Kimi Code provider and its OAuth refresh. I diffed the unit's own changes (commit dfb71c2 against its parent 91c6af4) for the changed executable paths: src/api/providers/kimi-code.ts, src/api/providers/fetchers/kimi-code.ts, and src/integrations/kimi-code/oauth.ts. Security boundary findings: - Secrets and personal data: The added lines contain no new logging of tokens, API keys, or credentials. The only log is the existing console.debug in prepareRequest, which records a error message string. OAuth tokens move only into SecretStorage (JSON-serialized credentials), as before. - Unvalidated input: New inputs (abort signals, and the forwarded CompletePromptOptions, which carries abortSignal and timeoutMs) reach existing code paths. Token responses still pass through tokenResponseSchema.parse. No new unvalidated input reaches an executed path. - Approval or allowlist bypass: No allowlist, approval, or auth-method gate was removed or weakened. canRefreshOAuth and the API-key auth branch are unchanged. The new sign-out fence in getAccessToken returns null while a clear is in progress, which fails closed. Behavior changes that are not security boundaries under this check: the refresh POST is no longer aborted on caller detach, and a failed store keeps the rotated pair in memory. These are concurrency and correctness design choices, documented in code comments. They do not expose data or bypass a control. The TLA+ model was not run, and the concurrency logic was reviewed only by reading, but that does not change this security-boundary result. No changed path contains a concrete defect that matches the stated failure conditions.
Full details: Persistence Integrity
-
Explanation
The changed persistence paths were checked in src/integrations/kimi-code/oauth.ts (diff against origin/main, which includes the u0 and u1 ancestor changes). No changed path meets the FAIL condition. Evidence: - Every SecretStorage call is awaited: store (line 308), the rollback get and delete (lines 326-328), the invalid_grant delete (line 434), the sign-out delete (line 359), and the corrupt-value delete in loadCredentials (line 283). - Credential writes run through queueCredentialWrite(), so saves run one at a time. saveCredentials() returns the queued promise and its callers await it. - A failed store keeps the rotated pair in memory (writeCredentials, catch block) and rethrows. The error reaches the waiters through awaitRefresh(), so the failure is not silent. Before this change, a failed store dropped the rotated pair. The change reduces loss. - Sign-out bumps the generation and sets a fence. The refresh path checks ownsThisRefresh() inside the queued write, so a stale refresh does not re-install deleted credentials. - The rollback path (read, compare, delete) is not atomic. The code comment states this residual window. A trigger needs a second extension host that shares the secret, or a write that lands between the second read and the delete. Inside this host, the chain orders the saves. Observations that do not change the verdict: - refreshController is never aborted in the file. The comment that says the shared POST aborts after every waiter detaches does not match the code. This does not cause data loss. It means the POST is never cancelled, which keeps the rotated pair safe. - The polling path (line 588) drops device tokens that arrive after a cancel. This matches the user's cancel intent. Nothing is written, so existing credentials are not affected. Limits: I did not run the test suite or TLA+ model. The check covers static review of the changed code only.
Full details: Lifecycle Resource Cleanup
-
Explanation
The PR diff (base 91c6af4 to HEAD dfb71c2) changes the Kimi Code provider, its model fetcher, and the OAuth manager. I checked each changed lifecycle path for a leaked listener, timer, watcher, or task, and for duplicate work after cancel, sign-out, or restart. I found no path that meets the FAIL condition. Checks performed: - postForm (oauth.ts ~L91-140): Every success path returns a settle() handle. The three callers (requestDeviceAuthorization, requestDeviceToken, refreshKimiCodeAccessToken) call settle() in finally. The timeout is cleared and the caller-signal listener is removed. The catch path calls settle() directly. - getKimiCodeModels (fetchers/kimi-code.ts ~L44-68): throwIfAborted runs before the timer starts. clearTimeout runs in finally. - awaitRefresh (oauth.ts ~L462-510): Each signaled waiter removes its abort listener on settle or abort. Waiters are removed from the Set on every path. An already-aborted signal does not register a listener. - Sign-out fence (clearCredentials): clearFenceCount is decremented in finally. The fence does not block the credential chain, so no deadlock appears. - Credential chain (queueCredentialWrite): The chain stores queued.catch(() => false). Rejections do not stall later writes. - KimiCodeHandler.prepareRequest: modelDiscoveryAttempted resets only on caller abort. This allows a retry on a later request. It does not start a second discovery inside the same flow. - modelCache single-flight (not changed by this PR): Waiter detach and flight abort are handled there. Notes that do not meet the FAIL condition: - refreshController is never aborted in production code. Only tests call abort() on it. The replacement branch in getAccessToken (L390) is therefore unreachable in production. The comments at oauth.ts L408-410 and L442-443 state that the shared POST aborts after all waiters detach. The code does not do that. The POST runs to completion or to the 10 s OAUTH_REQUEST_TIMEOUT_MS. No second POST starts, so no duplicate work occurs. The result is a stale comment and dead code, not a leak. - postForm's success path removes the caller abort forwarder right after headers arrive (L120). Its doc comment (L86-88) says the forwarder stays until settle(). The listener is still removed, and the timer still clears in settle(). This is a cancellation-contract mismatch, not a resource leak. Residual risk: runtime and timing behavior was not executed. The conclusions rest on static reading of the diff.
Resolution
None required for this check. Optional follow-up: align the comments at oauth.ts L86-88, L408-410, and L442-443 with the implemented behavior, or add production code that aborts refreshController. Remove the dead replacement branch if the controller is never aborted in production.
- Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
Changed-code mutation testingReport for PR head
Details: mutants, guidance, and reproductionChanged-code mutation testing
Focused tests
Reproduce locallyFrom a full checkout containing both commits: Mutation reports
The workflow uploads generated reports in the Advisory findings
|
Part of #2799 (split plan for #1311). Unit u3 of 4. Base for review: u1 (#2801).
This unit's own diff (provider-only)
kimi-code.ts,fetchers/kimi-code.ts,integrations/kimi-code/oauth.ts,kimi-code.spec.ts,kimi-code.oauth-cancellation.spec.ts,fetchers/__tests__/kimi-code.spec.ts,integrations/kimi-code/__tests__/oauth.spec.ts,model-catalog-adapters.spec.ts, anddocs/architecture/tla/KimiOAuthRefresh.{tla,cfg,Variant.cfg}.GitHub currently shows the ancestors' files too, because this branch is based on u1's head. Once #2800 and #2801 merge, the diff above is all this pull shows.
Why not independent right now
KimiCodeHandler extends the OpenAI handler u1 owns and calls
handleOpenAIRequestErrorfrom u0. After #2800 and #2801 land, this branch rebases to a provider-only, independently mergeable pull.Budget (own delta vs u1's head
91c6af4bb0)Changed executable lines: 229 (cap 500): oauth.ts 208, kimi-code.ts 29, fetcher 6. a+d ~2360 - the screens are exceeded because
oauth.spec.ts(1202 lines) and the two cancellation specs travel with the unit.Verification
201 rows pass;
tscclean;eslint --prune-suppressions --max-warnings=0clean; prettier clean.TLA+
TLC has not been run: the authoring machine has no Java. Run
TLA_JAR=<jar> ./check.sh KimiOAuthRefreshbefore this merges.Merge order
u0 (#2800) -> u1 (#2801) -> u2 (#2802) -> u3.